<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 会员模型
 */
class Menu extends Model
{
    public function getMenu($mid)
    {

        $mname = model('manager')->where('mid',$mid)->value('mname');
        $first = model('manager')->order('mid asc')->find();

        $where['status'] = 1;
        $where['pid'] = 0;
        if ($mname != $first->mname) {
            $rules = self::get_rules($mid);
            $where['id'] = array('in',$rules);
        }

        $firstCate = Db('menu')->where($where)->order('sort asc')->select();
        foreach ($firstCate as &$v) {
            $where['pid'] = $v['id'];
            $second = Db('menu')->where($where)->order('sort asc')->select();

            foreach ($second as &$vv) {
                $vv['url'] = url($vv['url']);
            }
            if ($second) {
                $v['url'] = '#';
                $v['_child'] = $second;
            } else {
                $v['url'] = url($v['url']);
                $v['_child'] = [];
            }
        }

        return $firstCate;
    }

    /**
     * 得到管理员的权限
     * @return array
     */
    public function get_rules($mid)
    {
        $rules = [];
        $auth_groups = Db::query("select * from zx_auth_group_access as a inner join zx_auth_group as g where a.group_id = g.id and a.uid = ?",[$mid]);
        foreach ($auth_groups as $v) {
            $rule = explode(',', trim($v['rules'], ','));
            $rules = array_merge($rules, $rule);
        }
        return $rules ;
    }
}
